from py2neo import Graph
import json

'''
执行cypher查询, 并按照不同问题的模板回复
'''


class ResultsSearcher:

    def __init__(self):
        """
        初始化连接参数
        """
        self.g = Graph("http://localhost:7474", username="neo4j", password="1008611")
        self.num_limit = 20

    def searcher(self, cyphers):
        """
        查询器
        :param cyphers:
        :return:
        """
        results = []
        for cypher in cyphers:
            question_type = cypher['question_type']
            queries = cypher['cypher']
            tmp_results = []
            for query in queries:
                # 执行cypher查询, 返回数据
                tmp_result = self.g.run(query).data()
                tmp_results += tmp_result
            answer = self.answer_template(question_type, tmp_results)
            if answer:
                results.append(answer)
        return results

    def answer_template(self, question_type, tmp_results):
        """
        回答模板
        :param question_type:
        :param tmp_results:
        :return:
        """
        answer = ''
        final_answer = ''
        # 判空
        if not tmp_results:
            return ''
        # 回答写入字符串
        # 去重
        tmp_ans = []
        for item in tmp_results:
            for k, v in item.items():
                if v not in tmp_ans:
                    tmp_ans.append(v)
                # answer += v + '\n'
        # tmp_ans = set(tmp_ans)
        for item in tmp_ans:
            answer += item + '\n'
        # 回答模板
        # 加载规则
        with open('../Knowledge_base/L2_Knowledge_base/rules/L2_rules.json', 'r', encoding='utf-8') as f:
            json_file_str = f.read()
            # loads要求字符串
            rules_dict = json.loads(json_file_str)
        for k, v in rules_dict.items():
            if k == question_type:
                final_answer += question_type + ':' + '\n'
        final_answer += answer
        return final_answer
